
let divList = [];
let timer = null;
let dom = document.getElementsByClassName('container')[0];
let btns = document.getElementsByClassName('btnC')[0].getElementsByTagName('button');
let searchVal = document.querySelector('#search');
btns[0].addEventListener('click',()=>{
    let value = searchVal.value.trim();
    if(!value){
       alert('请输入内容');
       return;
    }
    reset();
    preOrder(dom);
    changeColor(value);
},false);
btns[1].addEventListener('click',()=>{
    let value = searchVal.value.trim();
    if(!value){
       alert('请输入内容');
       return;
    }
    reset();
    postOrder(dom);
    changeColor(value);
},false);
btns[2].addEventListener('click',()=>{
    let value = searchVal.value.trim();
    if(!value){
       alert('请输入内容');
       return;
    }
    console.log(dom);
    reset();
    traverseDF(dom);
    changeColor(value);
},false);

btns[3].addEventListener('click',()=>{
    let value = searchVal.value.trim();
    if(!value){
       alert('请输入内容');
       return;
    }
    console.log(dom);
    reset();
    traverseBF(dom);
    changeColor(value);
},false);
// 前序遍历
function preOrder(node){
   if(!(node == null)){
      divList.push(node);
      for(let i=0;i<node.children.length;i++){
         preOrder(node.children[i]);
      }
   }
}

// 后序排列
function postOrder(node){
    if(!(node == null)){
       for(let i=0;i<node.children.length;i++){
        postOrder(node.children[i]);
       }
       divList.push(node);
    }
  }
// 深度查询  和后续排列一模一样 就是后续排列
function traverseDF(node){
    if(!(node == null)){
       for(let i=0;i<node.children.length;i++){
         traverseDF(node.children[i]);
       }
       divList.push(node);
    }
}
// 广度查询
function traverseBF(node){
    let queue = new Queue();
    queue.enqueue(node);
    let current = queue.dequeue();
    console.log(current);
    while(current){
       for(let i=0;i<current.children.length;i++){
        queue.enqueue(current.children[i]);
       } 
       divList.push(current);
       current = queue.dequeue();
    }
}
// 改变颜色
function changeColor(val){
    let i =0;
  
    timer = setInterval(() => {
        if(i<divList.length){
            if(divList[i].childNodes[0].nodeValue.trim() == val){
                divList[i].style.background = 'red';
            }else{
                divList[i].style.background = 'blue';
            }
            i++;
        }else{
           clearInterval(timer);
        }
    }, 500);

}

//清除样式
function reset(){
    divList = [];
    clearInterval(timer);
    let divs= document.getElementsByTagName('div');
    for(let i=0;i<divs.length;i++){
      divs[i].style.background = '#fff';
    }
}